package com.zht.user_manger.controller;

import cn.hutool.http.server.HttpServerRequest;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zht.user_manger.common.ErrorCode;
import com.zht.user_manger.common.ResponseEntity;
import com.zht.user_manger.common.ResponseResult;
import com.zht.user_manger.common.annotation.AuthCheck;
import com.zht.user_manger.constant.UserConstant;
import com.zht.user_manger.exception.BusinessException;
import com.zht.user_manger.objectmodel.dto.User.*;
import com.zht.user_manger.objectmodel.entity.User;
import com.zht.user_manger.objectmodel.vo.User.UserListResponse;
import com.zht.user_manger.objectmodel.vo.User.UserProfileResponse;
import com.zht.user_manger.objectmodel.vo.User.UserVo;
import com.zht.user_manger.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.zht.user_manger.service.impl.UserServiceImpl.SALT;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    /*==============================普通方法=========================================*/

    //用户登录
    @PostMapping("/login")
    @ApiOperation("登录账号")
    public ResponseEntity<UserProfileResponse> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserProfileResponse userProfileResponse = userService.userLogin(userAccount, userPassword, request);
        return ResponseResult.success(userProfileResponse);
    }

    //用户注册
    @PostMapping("/register")
    @ApiOperation("注册账号")
    public ResponseEntity<Long> userRegister(@RequestBody UserRegistrationRequest userRegistrationRequest) {
        if (userRegistrationRequest == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        String userAccount = userRegistrationRequest.getUserAccount();
        String userPassword = userRegistrationRequest.getUserPassword();
        String checkPassword = userRegistrationRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResponseResult.success(result);
    }

    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public ResponseEntity<Boolean> logout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResponseResult.success(result);
    }

    //获取当前登录用户的个人信息
    @GetMapping("/get/myselfInfo")
    @ApiOperation("获取个人信息")
    public ResponseEntity<UserProfileResponse> getUserVo(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResponseResult.success(userService.getLoginUserVO(user));
    }

    //用户修改个人信息
    @PostMapping("/update/myselfInfo")
    @ApiOperation("修改个人信息")
    public ResponseEntity<Boolean> updateMyself(@RequestBody UserProfileUpdateRequest userProfileUpdateRequest, HttpServletRequest request) {
        if(userProfileUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userProfileUpdateRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        return ResponseResult.success(result);
    }

    //查询用户列表
    @PostMapping("/query/userList")
    @ApiOperation("查询用户列表")
    public ResponseEntity<Page<UserListResponse>> queryUserList(@RequestBody UserListQueryRequest userListQueryRequest) {
        if(userListQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userListQueryRequest.getCurrent();
        long size = userListQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size), userService.getQueryWrapper(userListQueryRequest));
        Page<UserListResponse> userListResponsePage = new Page<>(current, size, userPage.getTotal());
        List<UserListResponse> userVO = userService.getUserVOList(userPage.getRecords());
        userListResponsePage.setRecords(userVO);
        return ResponseResult.success(userListResponsePage);
    }

    //查询用户信息详情
    @GetMapping("/query/userDetail")
    @ApiOperation("查询用户详情")
    public ResponseEntity<UserVo> queryUserDetail(Long userId) {
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(userId);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResponseResult.success(userVo);
    }

    /**
     * 方法注释 接口 输入 输出
     * 1.用户个人（注册 登录 退出登录 获取个人信息 修改个人信息 查询他人信息(分页) ）
     * 注册-》输入：账号+两次密码UserRegisterDto  返回：boolean
     * 登录-》输入：账号+密码UserLoginDto    输出：用户脱敏信息UserVo
     * 退出登录-》输入：id       输出：boolean
     * 获取个人信息-》输入：无从session中获取  输出：用户脱敏信息UserVo
     * 修改个人信息-》输入：用户修改的信息UserUpdateMyDto 输出：boolean
     * 模糊信息查询-》输入：UserQueryDto 输出：List<UserVoForList>
     * 查询他人信息-》输入：id  输出：UserVo
     *
     * 2.管理员（同上在外 创建新用户 更新用户状态 删除用户（批量） 查询用户列表（分页））
     * -》输入： 输出：
     * -》输入： 输出：
     * -》输入： 输出：
     */
    /*==============================管理员特有方法=========================================*/
    @PostMapping("/manger/add")
    @ApiOperation("管理员添加用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public ResponseEntity<Long> addUser(@RequestBody UserCreationRequest userCreationRequest) {
        if (userCreationRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userCreationRequest, user);
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        if (!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResponseResult.success(user.getId());
    }

    @PostMapping("/manger/delete")
    @ApiOperation("管理员删除用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public ResponseEntity<Boolean> updateUser(@RequestBody UserDeletionRequest userDeletionRequest) {
        if (userDeletionRequest == null || userDeletionRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.removeById(userDeletionRequest.getId());
        return ResponseResult.success(result);
    }

    @PostMapping("/manger/deleteBatch")
    @ApiOperation("管理员批量删除用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public ResponseEntity<Boolean> deleteBatchUser(@RequestBody List<UserDeletionRequest>  userDeletionRequestList) {
        if (userDeletionRequestList == null || userDeletionRequestList.size() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"列表为空");
        }
        boolean result = userService.removeByIds(userDeletionRequestList);
        return ResponseResult.success(result);
    }

    @PostMapping("/manger/update")
    @ApiOperation("管理员修改用户信息")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public ResponseEntity<Boolean> deleteUser(@RequestBody UserManagementUpdateRequest  userManagementUpdateRequest) {
        if (userManagementUpdateRequest == null || userManagementUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userManagementUpdateRequest, user);
        boolean result = userService.updateById(user);
        if (!result) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResponseResult.success(true);
    }

    //查询用户列表
    @GetMapping("/manger/query/userList")
    @ApiOperation("管理员查询用户列表")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public ResponseEntity<Page<UserListResponse>> queryUserListForManger(UserListQueryRequest userListQueryRequest) {
        if(userListQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userListQueryRequest.getCurrent();
        long size = userListQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size), userService.getQueryWrapper(userListQueryRequest));
        Page<UserListResponse> userListResponsePage = new Page<>(current, size, userPage.getTotal());
        List<UserListResponse> userVO = userService.getUserVOList(userPage.getRecords());
        userListResponsePage.setRecords(userVO);
        return ResponseResult.success(userListResponsePage);
    }


}
